import hyRequest from '@/service'
import { ContentType } from '@/service/config'
import { ElLoading } from 'element-plus'

enum Api {
  OSS = 'upload/getAwsAuth'
}

export default {
  // 初始化oss
  initOss(fileName: string) {
    return hyRequest.post({
      url: Api.OSS,
      data: { fileName },
      isFormData: true
    })
  },

  // 移动云直传
  async upload(file: any): Promise<string> {
    const loading = ElLoading.service({
      lock: true,
      text: '文件上传中',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve) => {
      if (!file) {
        return setTimeout(() => loading.close(), 500)
      }
      const { data } = await this.initOss(file.name)
      const { objectKey, uploadUrl } = data
      const arr = objectKey.split('.')
      const fileType = arr[arr.length - 1]

      await hyRequest.put(<ContentType>{
        url: uploadUrl,
        data: file,
        otherUrl: true,
        xAmzAcl: true,
        fileType
      })

      setTimeout(() => loading.close(), 500)
      resolve(`${uploadUrl.split('?')[0]}`)
    })
  }
}
